const path = require('path');
const TerserPlugin = require('terser-webpack-plugin');

module.exports = (env, argv) => {
    const isProduction = argv.mode === 'production';
    
    return {
        entry: './src/plugin.js',
        
        output: {
            filename: 'plugin.js',
            path: path.resolve(__dirname, 'assets'),
            clean: true,
            library: {
                type: 'umd',
                name: 'GitbookPluginGitcodeIssueFeedback'
            },
            globalObject: 'this'
        },
        
        module: {
            rules: [
                {
                    test: /\.js$/,
                    exclude: /node_modules/,
                    use: {
                        loader: 'babel-loader',
                        options: {
                            cacheDirectory: true,
                            cacheCompression: false
                        }
                    }
                },
                {
                    test: /\.css$/,
                    use: [
                        'style-loader',
                        {
                            loader: 'css-loader',
                            options: {
                                modules: false,
                                sourceMap: !isProduction
                            }
                        }
                    ]
                }
            ]
        },
        
        optimization: {
            minimize: isProduction,
            minimizer: [
                new TerserPlugin({
                    terserOptions: {
                        compress: {
                            drop_console: isProduction,
                            drop_debugger: isProduction,
                            pure_funcs: isProduction ? ['console.log'] : []
                        },
                        mangle: {
                            reserved: ['BugReporter']
                        }
                    },
                    extractComments: false
                })
            ],
            splitChunks: false
        },
        
        devtool: isProduction ? 'source-map' : 'eval-source-map',
        
        resolve: {
            extensions: ['.js', '.json'],
            alias: {
                '@': path.resolve(__dirname, 'src')
            },
            fallback: {
                "path": false,
                "fs": false,
                "util": false
            }
        },
        
        externals: {
            'gitbook': 'gitbook'
        },
        
        performance: {
            hints: isProduction ? 'warning' : false,
            maxEntrypointSize: 512000,
            maxAssetSize: 512000
        },
        
        stats: {
            colors: true,
            modules: false,
            children: false,
            chunks: false,
            chunkModules: false
        }
    };
};
